package com.yiya.ms.action;

import java.beans.PropertyEditorSupport;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.Merchant;
import com.yiya.bean.Payment;
import com.yiya.bean.SysUser;
import com.yiya.model.PaymentModel;
import com.yiya.service.MerchantService;
import com.yiya.service.PaymentService;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/payment")
public class PaymentAction extends BaseAction {
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(MerchantAction.class);

	@Autowired
	private PaymentService paymentService;
	
	@Autowired
	private MerchantService merchantService;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			public void setAsText(String value) {
				try {
					setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
				} catch (ParseException e) {
					setValue(null);
				}
			}

			public String getAsText() {
				return new SimpleDateFormat("yyyy-MM-dd")
						.format((Date) getValue());
			}
		});
	}

	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("payment/payment", context);
	}

	@RequestMapping("/dataList")
	public void datalist(PaymentModel model, HttpServletResponse response)
			throws Exception {
		List<Payment> payments = paymentService.queryByList(model);
		int count = paymentService.queryByCount(model);
		
		// 设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("rows", payments);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);

	}

	@RequestMapping("/save")
	public void save(Payment bean, HttpServletRequest request,
			HttpServletResponse response) {
		if (bean.getId() == null) {
			paymentService.add(bean);
		} else {
			paymentService.update(bean);
		}
		sendSuccessMessage(response, "保存成功");
	}

	@RequestMapping("/getId")
	public void getId(Integer id, HttpServletResponse response) {
		Map<String, Object> context = getRootMap();
		Payment payment = paymentService.queryById(id);
		if (payment == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", payment);
		HtmlUtil.writerJson(response, context);
	}

	@RequestMapping("/delete")
	public void delete(Integer[] id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SysUser user = SessionUtils.getUser(request);
		paymentService.delete(id, user);
		sendSuccessMessage(response, "删除成功");
	}

	/**
	 * 保存表格的更改
	 * 
	 * @param effectRow
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/commit")
	public void commit(HttpServletRequest request, HttpServletResponse response) {
		try {
			SysUser user = SessionUtils.getUser(request);
			String deleted = request.getParameter("deleted");
			if (deleted != null) {
				JSONArray deletedArray = JSONArray.fromObject(deleted);
				List<Payment> deletedList = convertJSONArrayToList(deletedArray);
				for (int i = 0; i < deletedList.size(); i++) {
					paymentService.delete(deletedList.get(i).getId(), user);
				}
			}

			String inserted = request.getParameter("inserted");
			if (inserted != null) {
				JSONArray insertedArray = JSONArray.fromObject(inserted);
				List<Payment> insertedList = convertJSONArrayToList(insertedArray);
				for (int i = 0; i < insertedList.size(); i++) {
					Payment payment = insertedList.get(i);
					payment = setDisplayName(payment);
					paymentService.add(payment);
				}
			}

			String updated = request.getParameter("updated");
			if (updated != null) {
				JSONArray updatedArray = JSONArray.fromObject(updated);
				List<Payment> updatedList = convertJSONArrayToList(updatedArray);
				for (int i = 0; i < updatedList.size(); i++) {
					Payment payment = updatedList.get(i);
					payment = setDisplayName(payment);
					paymentService.update(payment);
				}
			}
			sendSuccessMessage(response, "保存更改成功");
		} catch (Exception e) {
			// TODO: handle exception
			sendFailureMessage(response, "保存更改失败!");
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public void importExcel(@RequestParam MultipartFile payment,
			HttpServletResponse response) throws Exception {
		File tmpFile = new File(System.getProperty("java.io.tmpdir")
				+ System.getProperty("file.separator")
				+ payment.getOriginalFilename());
		String fileType = getFileNameSuffix(tmpFile.getName());
		if (fileType.equals(".xls")) {
			try {
				payment.transferTo(tmpFile);
				//paymentService.importExcel(tmpFile);
				sendSuccessMessage(response, "导入成功", "text/html");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				sendFailureMessage(response, "导入失败!", "text/html");
				e.printStackTrace();

			}
		} else {
			sendFailureMessage(response, "导入失败，文件格式需为xls!", "text/html");
		}
	}

	/**
	 * 获取文件后缀名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileNameSuffix(String fileName) {
		String type = null;
		if (fileName != null) {
			type = fileName.substring(fileName.lastIndexOf("."));
		}
		return type;
	}

	/**
	 * 将字符串类型的时间转换成Date类型
	 * 
	 * @param str
	 * @return
	 * @throws ParseException
	 */
	public static Date convertStringToDate(String str){
		try{
			if(!StringUtils.isEmpty(str)){
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				//yyyy-MM-dd的正则表达式
				String str1 ="^((((19|20)(([02468][048])|([13579][26]))\\-02\\-29))|((20[0-9][0-9])|(19[0-9][0-9]))\\-((((0[1-9])|(1[0-2]))\\-((0[1-9])|(1\\d)|(2[0-8])))|((((0[13578])|(1[02]))\\-31)|(((01,3-9])|(1[0-2]))\\-(29|30)))))$";
				if(str.matches(str1)){
					return sdf2.parse(str);
				}else{
					return sdf1.parse(str);
				}
			}else{
				return null;
			}
		}catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}

	/**
	 * 将JSONArray对象转换成List<Payment>对象
	 * 
	 * @param array
	 * @return
	 * @throws ParseException
	 */
	public List<Payment> convertJSONArrayToList(JSONArray array){
		List<Payment> list = new ArrayList<Payment>();
		for (int i = 0; i < array.size(); i++) {
			JSONObject paymentJO = JSONObject.fromObject(array.get(i));
			Payment payment = (Payment) JSONObject.toBean(paymentJO,
					Payment.class);
			
			Date paymentDate = convertStringToDate((String) paymentJO
					.get("paymentDate"));
			payment.setPaymentDate(paymentDate);
			
			list.add(payment);
		}
		return list;
	}
	
	/**
	 * 设置展示的名称
	 * @param payment
	 * @return
	 */
	public Payment setDisplayName(Payment payment){
		if(payment.getMerchantId()!=null){
			Merchant merchant = merchantService.queryById(payment.getMerchantId());
			payment.setMerchantName(merchant.getName());
		}
		if(payment.getPayStatus()==null||payment.getPayStatus()==0){
			payment.setPayStatusDisplay("否");
		}else{
			payment.setPayStatusDisplay("是");
		}
		if(payment.getTax()==null||payment.getTax()==0){
			payment.setTaxDisplay("否");
		}else{
			payment.setTaxDisplay("是");
		}
		return payment;
	}

}
